#!/usr/bin/env python3
"""
SSL证书生成工具
用于开发和测试环境的自签名证书
"""
import os
import subprocess
import sys
from pathlib import Path

def generate_ssl_cert():
    """生成自签名SSL证书"""
    cert_dir = Path("certs")
    cert_dir.mkdir(exist_ok=True)
    
    cert_file = cert_dir / "cert.pem"
    key_file = cert_dir / "key.pem"
    
    if cert_file.exists() and key_file.exists():
        print("SSL证书已存在")
        return str(cert_file), str(key_file)
    
    print("正在生成自签名SSL证书...")
    
    # 获取本机IP地址
    import socket
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    
    # 创建证书配置
    config_content = f"""[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
req_extensions = v3_req

[dn]
CN = {hostname}

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = {hostname}
IP.1 = 127.0.0.1
IP.2 = {local_ip}
"""
    
    config_file = cert_dir / "cert.conf"
    with open(config_file, 'w') as f:
        f.write(config_content)
    
    # 生成私钥
    subprocess.run([
        "openssl", "genrsa", "-out", str(key_file), "2048"
    ], check=True, capture_output=True)
    
    # 生成证书
    subprocess.run([
        "openssl", "req", "-new", "-x509", "-key", str(key_file),
        "-out", str(cert_file), "-days", "365",
        "-config", str(config_file), "-extensions", "v3_req"
    ], check=True, capture_output=True)
    
    print(f"SSL证书生成成功:")
    print(f"  证书文件: {cert_file}")
    print(f"  私钥文件: {key_file}")
    print(f"  配置文件: {config_file}")
    
    return str(cert_file), str(key_file)

def create_env_file():
    """创建环境配置文件"""
    cert_file, key_file = generate_ssl_cert()
    
    env_content = f"""# SSL证书配置
SSL_CERTFILE={cert_file}
SSL_KEYFILE={key_file}
FORCE_HTTPS=true

# 其他安全配置
SECURITY_HSTS_ENABLED=true
SECURITY_CSP_ENABLED=true

# CORS配置（根据需要修改）
CORS_ORIGINS=["http://localhost:3000", "http://localhost:8080", "https://yourdomain.com"]
"""
    
    with open(".env.security", 'w') as f:
        f.write(env_content)
    
    print(f"\n安全配置已保存到 .env.security")
    print("请将此文件内容复制到您的 .env 文件中")

if __name__ == "__main__":
    try:
        create_env_file()
    except subprocess.CalledProcessError as e:
        print(f"错误: 需要安装 OpenSSL")
        print("在 macOS 上: brew install openssl")
        print("在 Ubuntu 上: sudo apt-get install openssl")
        sys.exit(1)
    except Exception as e:
        print(f"生成证书时发生错误: {e}")
        sys.exit(1)